package com.changgou.auth.config;

import com.changgou.entity.Result;
import com.changgou.user.feign.UserFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserFeign userFeign;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
//        List<GrantedAuthority> authorities=new ArrayList<>();
//
//        authorities.add(new SimpleGrantedAuthority("ROLE_USER"));

        //通过feign调用用户服务 获取用户信息
        Result<com.changgou.user.pojo.User> result=userFeign.findByUsername(s);

        //判断feign调用服务的状态
        if (result==null||!result.isFlag()||result.getData()==null){
            return null;
        }

        //获取用户信息
        com.changgou.user.pojo.User userInfo = result.getData();
        //设置用户权限信息
        List<GrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority("ROLE_USER"));

        return new User(userInfo.getUsername(),userInfo.getPassword(),authorities);
    }
}
